package com.iwhalecloud.bss.kite.cucc.manager.scene.service.operate;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstDiscount;
import com.iwhalecloud.bss.kite.manager.scene.service.operate.OperateInstService;
import com.iwhalecloud.bss.kite.manager.transaction.TransactionContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 折扣实例处理类
 */
@Service("manager.LocalOperateOfferInstDiscountService")
public class LocalOperateOfferInstDiscountService extends OperateInstService {

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    /**
     * 添加折扣审批实例处理
     *
     * @param sceneInstId
     * @param prodInstId
     * @param stopType
     * @return
     */
    @Validated
    public List<KiteOfferInstDiscount> addOfferInstDiscount(String sceneInstId, String custId, String offerInstId, String discountJson) {
        List<KiteOfferInstDiscount> offerInstDiscounts = JsonUtils.parseArray(discountJson,
            KiteOfferInstDiscount.class);
        if (KiteListUtils.isEmpty(offerInstDiscounts)) {
            return Lists.newArrayList();
        }
        List<KiteOfferInstDiscount> kiteOfferInstDiscountList = querySceneInstService.listOfferInstDiscounts(custId, offerInstId);

        if (KiteListUtils.isEmpty(kiteOfferInstDiscountList)) {
            kiteOfferInstDiscountList = new ArrayList<>();
        }

        for (KiteOfferInstDiscount discount : offerInstDiscounts) {
            discount.setOfferObjInstRelId(SeqUtils.getNext("SEQ_DISCOUNT_INST_ID"));
            operateSceneInstService.addOfferInstDiscount(sceneInstId, discount, discount.getOfferInstId(), RelType.OFFER_OBJ_REL_TYPE_180000, ActionType.A, KeyConsts.OFFER_DISCOUNT_ROLE, null);
        }

        return querySceneInstService.listOfferInstDiscounts(custId, offerInstId);
    }

    /**
     * 获取折扣审批信息
     *
     * @param sceneInstId
     * @param offerInstId
     * @return
     */
    public List<KiteOfferInstDiscount> listOfferInstDiscounts(String sceneInstId, String custId, String offerInstId) {
        List<KiteOfferInstDiscount> discountInfos = querySceneInstService.listOfferInstDiscounts(custId, offerInstId);
        if (discountInfos == null) {
            discountInfos = new ArrayList<>();
            return discountInfos;
        }
        if (!KiteStringUtils.isEmpty(offerInstId)) {
            discountInfos = discountInfos.stream().filter((contract) -> KiteStringUtils.equals(contract.getOfferInstId(), offerInstId))
                .collect(Collectors.toList());
        }
        return discountInfos;
    }

    /**
     * 删除折扣审批信息
     *
     * @param sceneInstId
     * @param prodInstId
     * @param stopType
     * @return
     */
    public List<KiteOfferInstDiscount> deleteOfferInstDiscount(String sceneInstId, String custId, String offerInstId, String discountInstId) {

        List<KiteOfferInstDiscount> kiteOfferInstDiscountList = querySceneInstService.listOfferInstDiscounts(custId, offerInstId);

        if (KiteListUtils.isEmpty(kiteOfferInstDiscountList)) {
            kiteOfferInstDiscountList = new ArrayList<>();
        }

        kiteOfferInstDiscountList.forEach(kiteOfferInstDiscount -> {
            if (KiteStringUtils.isEqual(discountInstId, kiteOfferInstDiscount.getOfferObjInstRelId())) {
                operateSceneInstService.deleteOfferInstDiscount(sceneInstId, kiteOfferInstDiscount.getOfferObjInstRelId());
            }
        });

        kiteOfferInstDiscountList = querySceneInstService.listOfferInstDiscounts(custId, offerInstId).stream()
            .filter(t -> KiteStringUtils.equals(t.getActionType().name(), KeyConsts.ACTION_TYPE_A))
            .collect(Collectors.toList());

        return kiteOfferInstDiscountList;
    }

    /**
     * 更新折扣审批实例处理
     *
     * @param sceneInstId
     * @param prodInstId
     * @param stopType
     * @return
     */
    @Validated
    public List<KiteOfferInstDiscount> entryOfferInstDiscount(String sceneInstId, String custId, String offerInstId, String discountJson) {
        List<KiteOfferInstDiscount> offerInstDiscounts = JsonUtils.parseArray(discountJson,
            KiteOfferInstDiscount.class);
        if (KiteListUtils.isEmpty(offerInstDiscounts)) {
            return Lists.newArrayList();
        }
        for (KiteOfferInstDiscount newDiscount : offerInstDiscounts) {
            List<KiteOfferInstDiscount> kiteOfferInstDiscountList = querySceneInstService.listOfferInstDiscounts(custId, newDiscount.getOfferInstId());

            if (KiteListUtils.isEmpty(kiteOfferInstDiscountList)) {
                kiteOfferInstDiscountList = new ArrayList<KiteOfferInstDiscount>();
            }

            KiteOfferInstDiscount offerInstDiscount = kiteOfferInstDiscountList.stream().filter(discount -> KiteStringUtils.isEqual(discount.getOfferObjInstRelId(), newDiscount.getOfferObjInstRelId())).findFirst().orElse(null);
            if (!KiteObjectUtils.isEmpty(offerInstDiscount)) {
                offerInstDiscount.setDiscountFileUrl(newDiscount.getDiscountFileUrl());
                if (KiteStringUtils.isEmpty(newDiscount.getDiscountOrderId())) {
                    // 编码规则： YL（固定值）+年月日（例：20201114）+4位序列
                    String reqDiscount = SeqUtils.getNext("SEQ_DISCOUNT_ORDER_ID");
                    String time = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_FORMAT_8);
                    String discountOrderId = "YL" + time + reqDiscount;
                    offerInstDiscount.setDiscountOrderId(discountOrderId);
                } else {
                    offerInstDiscount.setDiscountOrderId(newDiscount.getDiscountOrderId());
                }
                offerInstDiscount.setDiscountName(newDiscount.getDiscountName());
                offerInstDiscount.setDiscountType(newDiscount.getDiscountType());
            }
            else {
                offerInstDiscount = new KiteOfferInstDiscount();
                if (KiteStringUtils.isEmpty(newDiscount.getDiscountOrderId())) {
                    // 编码规则： YL（固定值）+年月日（例：20201114）+4位序列
                    String reqDiscount = SeqUtils.getNext("SEQ_DISCOUNT_ORDER_ID");
                    String time = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_FORMAT_8);
                    String discountOrderId = "YL" + time + reqDiscount;
                    newDiscount.setDiscountOrderId(discountOrderId);
                }
                KiteBeanUtils.copyProperties(newDiscount, offerInstDiscount);
                offerInstDiscount.setOfferObjInstRelId(SeqUtils.getNext("SEQ_DISCOUNT_INST_ID"));
            }
            offerInstDiscount.setInstType(InstType.OFFER_INST_DISCOUNT);

            KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, newDiscount.getOfferInstId());
            if (KiteObjectUtils.isEmpty(offerInst)) {
                ErrorConsts.OFFER_INST_NOT_EXIST.throwOut(newDiscount.getOfferInstId(), custId);
            }
            // 没有账户明细关系，明细ID传销售品id
            String offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId).orElse("");
            // 添加之前删除之前上传的文件
            kiteOfferInstDiscountList.forEach(kiteOfferInstDiscount -> {
                operateSceneInstService.deleteOfferInstDiscount(sceneInstId, kiteOfferInstDiscount.getOfferObjInstRelId());
            });

            operateSceneInstService.addOfferInstDiscount(sceneInstId, offerInstDiscount, offerInstDiscount.getOfferInstId(), RelType.OFFER_OBJ_REL_TYPE_180000, ActionType.A, KeyConsts.OFFER_DISCOUNT_ROLE, offerId);
        }

        List<KiteOfferInstDiscount> kiteOfferInstDiscountList = Lists.newArrayList();
        List<KiteOfferInst> giftOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
        if (KiteListUtils.isNotEmpty(giftOfferInsts)) {
            KiteOfferInst offerInst = giftOfferInsts.get(0);
            kiteOfferInstDiscountList
                .addAll(querySceneInstService.listOfferInstDiscounts(custId, offerInst.getOfferInstId()));
        }
        else {
            List<KiteOfferInst> mainOfferInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
            for (KiteOfferInst offerInst : mainOfferInsts) {
                kiteOfferInstDiscountList
                    .addAll(querySceneInstService.listOfferInstDiscounts(custId, offerInst.getOfferInstId()));
            }
        }
        kiteOfferInstDiscountList = kiteOfferInstDiscountList.stream()
            .filter(t -> KiteStringUtils.equals(t.getActionType().name(), KeyConsts.ACTION_TYPE_A))
            .collect(Collectors.toList());
        return kiteOfferInstDiscountList;
    }
    /**
     * 更新折扣审批实例处理
     *
     * @param sceneInstId
     * @param prodInstId
     * @param stopType
     * @return
     */
    @Validated
    public List<KiteOfferInstDiscount> finDoopentryOfferInstDiscount(String sceneInstId, String custId, String offerInstId, String discountJson) {
        List<KiteOfferInstDiscount> offerInstDiscounts = JsonUtils.parseArray(discountJson,
            KiteOfferInstDiscount.class);
        if (KiteListUtils.isEmpty(offerInstDiscounts)) {
            return Lists.newArrayList();
        }
        for (KiteOfferInstDiscount newDiscount : offerInstDiscounts) {
            List<KiteOfferInstDiscount> kiteOfferInstDiscountList = querySceneInstService.listOfferInstDiscounts(custId, newDiscount.getOfferInstId());

            if (KiteListUtils.isEmpty(kiteOfferInstDiscountList)) {
                kiteOfferInstDiscountList = new ArrayList<KiteOfferInstDiscount>();
            }

            KiteOfferInstDiscount offerInstDiscount = kiteOfferInstDiscountList.stream().filter(discount -> KiteStringUtils.isEqual(discount.getOfferObjInstRelId(), newDiscount.getOfferObjInstRelId())).findFirst().orElse(null);
            if (!KiteObjectUtils.isEmpty(offerInstDiscount)) {
                offerInstDiscount.setDiscountFileUrl(newDiscount.getDiscountFileUrl());
                if (KiteStringUtils.isEmpty(newDiscount.getDiscountOrderId())) {
                    // 编码规则： YL（固定值）+年月日（例：20201114）+4位序列
                    String reqDiscount = SeqUtils.getNext("SEQ_DISCOUNT_ORDER_ID");
                    String time = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_FORMAT_8);
                    String discountOrderId = "YL" + time + reqDiscount;
                    offerInstDiscount.setDiscountOrderId(discountOrderId);
                } else {
                    offerInstDiscount.setDiscountOrderId(newDiscount.getDiscountOrderId());
                }
                offerInstDiscount.setDiscountName(newDiscount.getDiscountName());
                offerInstDiscount.setDiscountType(newDiscount.getDiscountType());
            }
            else {
                offerInstDiscount = new KiteOfferInstDiscount();
                if (KiteStringUtils.isEmpty(newDiscount.getDiscountOrderId())) {
                    // 编码规则： YL（固定值）+年月日（例：20201114）+4位序列
                    String reqDiscount = SeqUtils.getNext("SEQ_DISCOUNT_ORDER_ID");
                    String time = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_FORMAT_8);
                    String discountOrderId = "YL" + time + reqDiscount;
                    newDiscount.setDiscountOrderId(discountOrderId);
                }
                KiteBeanUtils.copyProperties(newDiscount, offerInstDiscount);
                offerInstDiscount.setOfferObjInstRelId(SeqUtils.getNext("SEQ_DISCOUNT_INST_ID"));
            }
            offerInstDiscount.setInstType(InstType.OFFER_INST_DISCOUNT);

            KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, newDiscount.getOfferInstId());
            if (KiteObjectUtils.isEmpty(offerInst)) {
                ErrorConsts.OFFER_INST_NOT_EXIST.throwOut(newDiscount.getOfferInstId(), custId);
            }
            // 没有账户明细关系，明细ID传销售品id
            String offerId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getOfferId).orElse("");
            // 添加之前删除之前上传的文件
            kiteOfferInstDiscountList.forEach(kiteOfferInstDiscount -> {
                operateSceneInstService.deleteOfferInstDiscount(sceneInstId, kiteOfferInstDiscount.getOfferObjInstRelId());
            });

            operateSceneInstService.addOfferInstDiscount(sceneInstId, offerInstDiscount, offerInstDiscount.getOfferInstId(), RelType.OFFER_OBJ_REL_TYPE_180000, ActionType.A, KeyConsts.OFFER_DISCOUNT_ROLE, offerId);
        }

        List<KiteOfferInstDiscount> kiteOfferInstDiscountList = Lists.newArrayList();
        return kiteOfferInstDiscountList;
    }
}
